/**
 * Copyright (c) 2021 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */
package io.renren.modules.stat.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.stat.dao.StatChannelConfDao;
import io.renren.modules.stat.dto.StatChannelConfDTO;
import io.renren.modules.stat.entity.StatChannelConfEntity;
import io.renren.modules.stat.service.StatChannelConfService;
import io.renren.modules.stat.service.StatChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 栏目管理
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service
public class StatChannelConfServiceImpl extends CrudServiceImpl<StatChannelConfDao, StatChannelConfEntity, StatChannelConfDTO> implements StatChannelConfService {

    @Autowired
    @Lazy
    private StatChannelService statChannelService;

    @Override
    public QueryWrapper<StatChannelConfEntity> getWrapper(Map<String, Object> params) {
        QueryWrapper<StatChannelConfEntity> wrapper = new QueryWrapper<>();

        wrapper.orderByAsc("sort");

        return wrapper;
    }

    @Override
    public List<StatChannelConfDTO> list(Map<String, Object> params) {
        List<StatChannelConfEntity> entityList = baseDao.selectList(getWrapper(params));

        return ConvertUtils.sourceToTarget(entityList, StatChannelConfDTO.class);
    }

    @Override
    public StatChannelConfDTO getByChannel(Long channelId) {
        StatChannelConfEntity entity = baseDao.getByChannel(channelId);
        if (entity == null) {
            entity = new StatChannelConfEntity();
            entity.setChannelId(channelId);
            Map<String, Object> params = new HashMap<>();
            params.put("channelId", String.valueOf(channelId));
            List<String> columns = statChannelService.columns(params);
            JSONObject conf = new JSONObject();
            for (String column : columns) {
                conf.set(column, "0,0");
            }
            entity.setConf(conf.toString());
        }
        return ConvertUtils.sourceToTarget(entity, StatChannelConfDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long[] ids) {
        baseDao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByChannel(Long channelId) {
        baseDao.deleteByChannel(channelId);
    }
}